//
//  LocationView.m
//  Estate
//
//  Created by heyong on 16/7/1.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "LocationView_jl.h"

@interface LocationView_jl ()
// 获取当前放大比例
@property (nonatomic, assign) CGFloat newScale;

// 图片的宽
@property (assign, nonatomic) CGFloat imageWidth;

// 图片的高
@property (assign, nonatomic) CGFloat imageHeight;

@end

@implementation LocationView_jl

- (UIView *)flagView{
    if(_flagView==nil){
        _flagView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 12, 12)];
        _flagView.backgroundColor=[UIColor redColor];
    }
    return _flagView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        
    }
    return self;
    
}
-(void)createUIWithImage:(UIImage *)image ImgUrl:(NSString *)imageUrl
{
    if (imageUrl == nil && image == nil) {
        [self.flagView removeFromSuperview];
        //避免都传空
        return;
    }
    self.backgroundColor=[UIColor whiteColor];
    
    //    得到图片的宽度 高度
    CGFloat imageH=image.size.height;
    self.imageHeight = image.size.height;
    CGFloat imageW=image.size.width;
    self.imageWidth = image.size.width;
    //比例
    //    CGFloat biz=imageH/imageW;
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-140)];
    //    NSLog(@"sw:%.2f,wh:%.2f",self.bounds.size.width,self.bounds.size.height);
    _scrollView.backgroundColor=[UIColor whiteColor];
    _scrollView.delegate = self;
    _scrollView.minimumZoomScale = 1;
    _scrollView.maximumZoomScale = 3;
    
    //    _scrollView.showsHorizontalScrollIndicator = NO;
    //    _scrollView.showsVerticalScrollIndicator = NO;
    
    CGFloat w=DEF_SCREEN_WIDTH;
    //得到图片缩放后的高，宽为固定
    CGFloat biz_w= imageW/w;
    
    self.BLscale = biz_w;
    
    CGFloat h_1=imageH/biz_w;
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, h_1)];
    //    NSLog(@"sw:%.2f,wh:%.2f",w,h);
    
    self.imageView.backgroundColor=[UIColor whiteColor];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.userInteractionEnabled = YES;
    
    /*
     *   绘制网格线条
     **/
    for (int i=1; i<4; i++) {
        CALayer *headLine = [CALayer layer];
        headLine.frame = CGRectMake(0, h_1/4*i, w, 1);
        headLine.backgroundColor = [UIColor colorWithRed:0.69 green:0.27 blue:0.12 alpha:1.00].CGColor;
        [self.imageView.layer addSublayer:headLine];
        
    }
    for (int i=1; i<4; i++) {
        CALayer *headLine = [CALayer layer];
        headLine.frame = CGRectMake(w/4*i,0,1, h_1);
        headLine.backgroundColor = [UIColor colorWithRed:0.69 green:0.27 blue:0.12 alpha:1.00].CGColor;
        [self.imageView.layer addSublayer:headLine];
    }
    
    if (imageUrl == nil) {
        if(self.imageWidth >8000.){
            CGFloat w=2000;
            //得缩放成2000的比例
            CGFloat biz_w= imageW/w;
            CGFloat h_1=imageH/biz_w;
            
            //和屏幕宽比例
            CGFloat w1=DEF_SCREEN_WIDTH;
            CGFloat biz_w1= w/w1;
            
            //总比例
            self.BLscale = biz_w*biz_w1;
            
            UIImage *img=[self imageByScalingAndCroppingForSize:CGSizeMake(w, h_1) withSourceImage:image];
            
            self.imageView.image = img;
            
        }else{
            self.imageView.image = image;

        }
        //本地图片
    }
    if (image == nil) {
        //设置加载网络图片
        //        [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        //
        //        }];
    }
    
    [self.scrollView addSubview:self.imageView];
    //添加手势
    //一个手指
    UITapGestureRecognizer *singleClickDog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singliDogTap:)];
    UITapGestureRecognizer *doubleClickTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    //两个手指
    UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handelTwoFingerTap:)];
    singleClickDog.numberOfTapsRequired = 1;
    singleClickDog.numberOfTouchesRequired = 1;
    doubleClickTap.numberOfTapsRequired = 2;//需要点两下
    twoFingerTap.numberOfTouchesRequired = 2;//需要两个手指touch
    [_imageView addGestureRecognizer:singleClickDog];
    [_imageView addGestureRecognizer:doubleClickTap];
    [_imageView addGestureRecognizer:twoFingerTap];
    //设置事件优先级
    [singleClickDog requireGestureRecognizerToFail:doubleClickTap];
    //如果双击了，则不响应单击事件
    [_scrollView setZoomScale:1];
    [self addSubview:_scrollView];
}


/**
 * 图片压缩到指定大小
 * @param targetSize 目标图片的大小
 * @param sourceImage 源图片
 * @return 目标图片
 */
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark - ScrollView Delegate
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}
//缩放系数(倍数)
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [scrollView setZoomScale:scale+0.01 animated:NO];
    [scrollView setZoomScale:scale animated:NO];
}
#pragma mark - 事件处理
//此方法暂时无用
-(void)singliDogTap:(UITapGestureRecognizer *)gestureRecognizer
{
    
    //点击图像定位
    if (gestureRecognizer.numberOfTapsRequired == 1)
    {
        CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
        self.flagView.frame=CGRectMake(point.x, point.y, 5, 5);
        [self.imageView addSubview:self.flagView];
        NSLog(@"x:%.2f,y:%2f",point.x,point.y);
        self.scale = self.scrollView.zoomScale;
        
        self.selectedX = point.x * self.BLscale;
        self.selectedY = point.y * self.BLscale;
       
        if (self.successBlock) {
            self.successBlock();
        }
        DeLog(@"存入坐标x：%.2f,y:%.2f", self.selectedX, self.selectedY);
    }
}


-(void)handleDoubleTap:(UITapGestureRecognizer *)gestureRecognizer{
    
    //点击一次或者两次
    if (gestureRecognizer.numberOfTapsRequired == 2) {
        //如果当前页面并未放大
        if(_scrollView.zoomScale == 1){
            float newScale = [_scrollView zoomScale] *2;
            CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
            [_scrollView zoomToRect:zoomRect animated:YES];
        }else{//已经放大
            float newScale = [_scrollView zoomScale]/2;
            CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
            [_scrollView zoomToRect:zoomRect animated:YES];
        }
    }
}

//两个手指点击 缩小
-(void)handelTwoFingerTap:(UITapGestureRecognizer *)gestureRecongnizer{
    if (_myBlock) {
        _myBlock(@"2手指");
    }
    float newScale = [_scrollView zoomScale]/2;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecongnizer locationInView:gestureRecongnizer.view]];
    [_scrollView zoomToRect:zoomRect animated:YES];
}

#pragma mark - 缩放大小获取方法
-(CGRect)zoomRectForScale:(CGFloat)scale withCenter:(CGPoint)center{
    CGRect zoomRect;
    //大小
    zoomRect.size.height = [_scrollView frame].size.height/scale;
    zoomRect.size.width = [_scrollView frame].size.width/scale;
    //原点
    zoomRect.origin.x = center.x - zoomRect.size.width/2;
    zoomRect.origin.y = center.y - zoomRect.size.height/2;
    return zoomRect;
}

// 回传位置
- (void)getX:(CGFloat)sX withY:(CGFloat)sY withScale:(CGFloat)scale {
    // 获取点击位置
    //    CGFloat pointX = sX * self.imageWidth / self.BLscale * scale;
    //    CGFloat pointY = sY * self.imageHeight / self.BLscale * scale;
    
    //5月22日 改动
    CGFloat pointX = sX / self.BLscale;
    CGFloat pointY = sY / self.BLscale;
    
    self.flagView.frame = CGRectMake(pointX, pointY, 5, 5);
    [self.imageView addSubview:self.flagView];
}

@end
